package com.rpay.admin.config.security;

import com.rpay.admin.util.render.JsonRender;
import com.rpay.common.vo.PcsResult;
import com.rpay.model.admin.RpayAdminUser;
import com.rpay.service.admin.impl.SecUserRoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 可在此类中增加session会话处理
 */
public class LoginSuccessHandler extends
        SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private JsonRender render;
    @Autowired
    private SecUserRoleServiceImpl secUserRoleService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
        //获得授权后可得到用户信息   可使用SUserService进行数据库操作  


        System.out.println("IP :" + getIpAddress(request));
        RpayAdminUser userDetails = (RpayAdminUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //一个用户所拥有的权限应该有且只有一个，暂时先按一个做
        //Region region = permissionService.getSonRegionForFront(regionCode);
        Map result = new HashMap();
//        result.put("is_city", is_city);
        result.put("is_city", false);
        result.put("realname", userDetails.getRealName());
        result.put("username", userDetails.getUsername());
        List<Map> modulelist = secUserRoleService.getRoleandNameByUser(userDetails);
        result.put("modulelist", modulelist);


        render.render(request, response, PcsResult.build(result));
    }

    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}  